package com.spider.im.chat.message.register;

import com.google.protobuf.Parser;
import com.spider.im.chat.annotation.MessageTypeHandler;
import com.spider.im.chat.message.AbstractMessageStrategy;
import com.spider.im.chat.proto.ChatProto;
import com.spider.im.common.aspect.BusinessException;
import com.spider.im.user.req.UserReq;
import com.spider.im.user.service.UserService;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@MessageTypeHandler(type = ChatProto.MessageType.REGISTER)
public class RegisterStrategy extends AbstractMessageStrategy<ChatProto.RegisterRequest> {

    @Resource
    private UserService  userService;

    @Override
    public Parser<ChatProto.RegisterRequest> getParser() {
        return ChatProto.RegisterRequest.parser();
    }

    @Override
    public void handle(ChannelHandlerContext ctx, ChatProto.RegisterRequest message) {

        log.info("注册用户: {}", message.getUsername());
        UserReq userReq = new UserReq();
        userReq.setUsername(message.getUsername());
        try {
            userService.register(userReq);
            sendResponse(ctx.channel(), getMessageWrapper(true, "注册成功"));
        } catch (BusinessException e) {
            log.warn("注册失败: {}", e.getMessage());
            sendResponse(ctx.channel(), getMessageWrapper(true, e.getMessage()));
        } catch (Exception e) {
            log.error("注册失败: {}", e.getMessage());
            sendResponse(ctx.channel(), getMessageWrapper(false, "注册失败"));
        }
    }


    /**
     * 构建消息包装
     *
     * @return
     */
    private static ChatProto.MessageWrapper getMessageWrapper(boolean success, String message) {
        ChatProto.Response response = ChatProto.Response.newBuilder()
                .setSuccess(success)
                .setMessage(message)
                .build();
        return ChatProto.MessageWrapper.newBuilder()
                .setType(ChatProto.MessageType.REGISTER)
                .setPayload(response.toByteString())
                .build();
    }
}
